<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-01-29 19:43:21
 * Desc:
 */

namespace app\core\util;

use app\core\exception\{BusinessException, ErrorCode};
use app\core\cache\{RedisCache, RedisKeys};
use app\core\log\Log4dd;

class PreVentRepeatSubmitUtil
{

    /**
     * Desc: 防重复提交，N秒内不允许重复提交
     * Date: 2020/1/29 19:49
     * Author: yiyu
     * @param $key
     * @param $second
     * @param int $errCode
     */
    public static function check($key, $second = 2, $errCode = ErrorCode::COMMON_PREVENT_REPEAT_SUBMIT)
    {
        // 2秒内不允许重复提交
        $nowTime = time();
        RedisCache::selectDB(config('redis_db_index.prevent_repeat_submit'));
        $key = RedisKeys::getPreVentRepeatSubmitKey($key);
        $value = RedisCache::getSet($key, $nowTime);
        RedisCache::expire($key, 3);
        if (!empty($nowTime) && ($nowTime - $value <= $second)) {
            RedisCache::expire($key, 3);
            $msg = "请求太频繁了，请稍后重试";
            Log4dd::info($msg, [$key, $nowTime, $value]);
            throw new BusinessException($errCode, $msg);
        }
    }

}